//
//  AGLHotView.m
//  滴滴快拍
//
//  Created by dllo on 16/5/21.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "AGLHotView.h"

@interface AGLHotView ()
<
UICollectionViewDelegate,
UICollectionViewDataSource
>

@property (nonatomic, strong) BaseCollectionView *hotCollection;
@property (nonatomic, strong) NSMutableArray *hotArr;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger refresh;
@property (nonatomic, strong) NSTimer *outTimer;


@end

@implementation AGLHotView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createView];
        [self createData];
    }
    return self;
}

- (void)createView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((self.frame.size.width - 15) / 2, self.frame.size.height / 2.5);
    layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 5;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    // 创建collection
    self.hotCollection = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) collectionViewLayout:layout];
    [self addSubview:self.hotCollection];
    //  设置代理
    self.hotCollection.delegate = self;
    self.hotCollection.dataSource = self;
    // 注册
    [self.hotCollection registerClass:[AGLChannelCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([AGLChannelCollectionCell class])];
    
    [self.hotCollection registerClass:[AGLTopicCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([AGLTopicCollectionCell class])];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.hotArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    //    NSLog(@"%@", NSStringFromClass([self.perContentArr[indexPath.item] class]));
    NSString *className = NSStringFromClass([self.hotArr[indexPath.item] class]);
    //    Class class = NSClassFromString(className);
    
    //    if ([[class class] isKindOfClass:[AGLChannel class]]) {
    if ([className isEqualToString:@"AGLChannel"]) {
        
        AGLChannelCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AGLChannelCollectionCell class]) forIndexPath:indexPath];
        AGLChannel *channel = self.hotArr[indexPath.item];
        cell.channel = channel;
        
        return cell;
        
    } else {
        AGLTopicCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AGLTopicCollectionCell class]) forIndexPath:indexPath];
        AGLTopic *topic = self.hotArr[indexPath.item];
        cell.topic = topic;
        
        return cell;
        
    }
    
}


#pragma mark 点击小cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *className = NSStringFromClass([self.hotArr[indexPath.item] class]);
    if ([className isEqualToString:@"AGLChannel"]) {
        AGLChannel *channel = self.hotArr[indexPath.item];
#pragma mark 视频详情block传值channel 3.
        // 后一个界面调用block
        self.block(channel.scid, channel.streambase);
        
        
    } else if ([className isEqualToString:@"AGLTopic"]) {
        AGLTopic *modal = self.hotArr[indexPath.item];
        if (modal.topicType) {
#pragma mark 视频详情block传值channel 3.
            // 后一个界面调用block
            NSString *topicnameStr = [modal.tagtopic componentsSeparatedByString:@"#"][1];
//            1.url编码
//            ios中http请求遇到汉字的时候，需要转化成UTF-8，用到的方法是：
            NSString * topicnameEncodingStr = [topicnameStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//            2.url解码
//            请求后，返回的数据，如何显示的是这样的格式：%3A%2F%2F，此时需要我们进行UTF-8解码，用到的方法是：
//            NSString *str = [model.album_name stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            self.topicBlock(modal.stpid, topicnameEncodingStr);
        } else {
            
            self.topicfaulseBlock(modal.stpid);
        }
    }
}


#pragma mark 请求数据

- (void)createData {
    
    self.refresh = 0;
    //1.下拉刷新
    self.hotCollection.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.page = 1;
        self.refresh++;
        //        if (_outTimer) {
        //            [_outTimer invalidate];
        //            _outTimer = nil;
        //        }
        //        self.outTimer = [NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(showNetWorkBad) userInfo:nil repeats:NO];
        [self recieveData];
    }];
    
    //2.上拉加载
    self.hotCollection.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self recieveData];
    }];
    // 马上进入刷新状态
    [self.hotCollection.mj_header beginRefreshing];
    
}
//-(void)showNetWorkBad{
//    if (_outTimer) {
//        [_outTimer invalidate];
//        _outTimer = nil;
//    }
//    [self.perContentCollection.mj_header endRefreshing];
//}

- (void)recieveData {
    //http://api.miaopai.com/m/v5_hot_channel.json?os=android&udid=0156a9d2-fb05-3001-83e2-e2592b043531&version=6.3.5&timestamp=1463472566844&unique_id=0156a9d2-fb05-3001-83e2-e2592b043531&per=20&page=1&token=&vend=miaopai&pname=com.yixia.videoeditor&uuid=0156a9d2-fb05-3001-83e2-e2592b043531&sinaad=1&channel=huawei&refresh=1&deviceId=0156a9d2-fb05-3001-83e2-e2592b043531
    //http://api.miaopai.com/m/v5_hot_channel.json?unique_id=0156a9d2-fb05-3001-83e2-e2592b043531&per=20&page=1&token=&vend=miaopai&pname=com.yixia.videoeditor&uuid=0156a9d2-fb05-3001-83e2-e2592b043531&sinaad=1&channel=huawei&refresh=2
    //http://api.miaopai.com/m/v5_hot_channel.json?per=20&page=1&token=&vend=miaopai&pname=com.yixia.videoeditor&uuid=0156a9d2-fb05-3001-83e2-e2592b043531&sinaad=1&channel=huawei&refresh=2
    
    //http://api.miaopai.com/m/v5_hot_channel.json?per=20&page=%ld&token=&vend=miaopai&pname=com.yixia.videoeditor&sinaad=1&refresh=%ld
    
    NSString *urlString = [NSString stringWithFormat:@"http://api.miaopai.com/m/v5_hot_channel.json?per=20&page=%ld&token=&vend=miaopai&pname=com.yixia.videoeditor&uuid=0156a9d2-fb05-3001-83e2-e2592b043531&sinaad=1&channel=huawei&refresh=%ld", self.page, self.refresh];

    
    // 请求collec内容
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self saveData:responseObject DataName:[NSString stringWithFormat:@"hot"]];

        NSDictionary *dic = responseObject;
        NSArray *result = dic[@"result"];
        
//        self.hotArr = [NSMutableArray array];
        NSMutableArray *array = [NSMutableArray array];
        
        for (NSDictionary *temp in result) {
            if ([temp[@"type"] isEqualToString:@"channel"]) {
                AGLChannel *channel = [[AGLChannel alloc] init];
                [channel setValuesForKeysWithDictionary:temp];
                [array addObject:channel];
            } else if ([temp[@"type"] isEqualToString:@"topic"]) {
                AGLTopic *topic = [[AGLTopic alloc] init];
                [topic setValuesForKeysWithDictionary:temp];
                [array addObject:topic];
            }
        }
        
        if (self.page == 1) {
            self.hotArr = [NSMutableArray arrayWithArray:array];
        } else {
            [self.hotArr addObjectsFromArray:array];
        }
        
        self.page += 1;
        // 刷新表格
        [self.hotCollection.mj_header endRefreshing];
        [self.hotCollection.mj_footer endRefreshing];
        [self.hotCollection reloadData];

        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"hot内容collection联网失败");
        [self.hotCollection.mj_header endRefreshing];
        [self.hotCollection.mj_footer endRefreshing];

        NSDictionary *dic = [self getDataWithDataName:[NSString stringWithFormat:@"hot"]];
        if (dic == nil) {
            NSLog(@"请连网啊亲");
        } else {
            NSArray *result = dic[@"result"];
            
            self.hotArr = [NSMutableArray array];
            
            for (NSDictionary *temp in result) {
                if ([temp[@"type"] isEqualToString:@"channel"]) {
                    AGLChannel *channel = [[AGLChannel alloc] init];
                    [channel setValuesForKeysWithDictionary:temp];
                    [self.hotArr addObject:channel];
                } else if ([temp[@"type"] isEqualToString:@"topic"]) {
                    AGLTopic *topic = [[AGLTopic alloc] init];
                    [topic setValuesForKeysWithDictionary:temp];
                    [self.hotArr addObject:topic];
                }
            }
            [self.hotCollection reloadData];
        }

        
    }];
    
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
